package com.xiaomi.shoppinglist

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Database(entities = [ShoppingItem::class], version = 1)
abstract class ShoppingListDatabase : RoomDatabase() {
    abstract fun shoppingItemDao(): ShoppingItemDao

    companion object {
        @Volatile
        private var INSTANCE: ShoppingListDatabase? = null

        fun getInstance(context: Context): ShoppingListDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    ShoppingListDatabase::class.java,
                    "shopping_list_database"
                ).build()
                INSTANCE = instance
                instance
            }
        }

        fun init(context: Context) {
            // 初始化数据库
            val db = getInstance(context)

            // 启动协程检查需要提醒的项
            CoroutineScope(Dispatchers.IO).launch {
                checkReminders(db)
            }
        }

        private suspend fun checkReminders(db: ShoppingListDatabase) {
            val items = db.shoppingItemDao().getRemindableItems()
            val currentTime = System.currentTimeMillis()

            for (item in items) {
                if (item.shouldRemind()) {
                    // 重置项的完成状态
                    item.resetCompletion()
                    db.shoppingItemDao().update(item)
                }
            }
        }
    }
}